﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace Frame
{
    public class XmlFileHelper
    {

        public static XmlDocument LoadXml(string path, string root_name)
        {
            XmlDocument xml = new XmlDocument();
            if (!File.Exists(path))//判断是否存在，不存在就创建
            {
                try
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                    //创建第一行描述信息，并且添加到doc文档中
                    XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "utf-8", null);
                    xml.AppendChild(dec);
                    //创建根节点
                    XmlElement rootEle = xml.CreateElement(root_name);
                    //将根节点添加到文档中
                    xml.AppendChild(rootEle);
                    xml.Save(path);
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                xml.Load(path);
            }
            return xml;
        }

        /// <summary>
        /// 查找子项，如果没有就添加
        /// </summary>
        /// <param name="node"></param>
        /// <param name="Name"></param>
        /// <returns></returns>
        public static XmlNode ScanChildElement(XmlDocument doc, XmlNode node, string Name)
        {
            XmlNode childNode = null;
            bool _find = false;
            foreach (XmlNode childEle in node.ChildNodes)
            {
                if(childEle.Name == Name)
                {
                    childNode = childEle;
                    _find = true;
                }
            }
            if(!_find)
            {
                childNode = doc.CreateElement(Name);
                node.AppendChild(childNode);               
            }
            return childNode;
        }
        
        public static XmlNode ScanChildElement(XmlDocument doc, XmlNode node, string Name, string text)
        {
            XmlNode childNode = null;
            bool _find = false;
            foreach (XmlNode cNode in node.ChildNodes)
            {
                if (cNode.Name == Name)
                {
                    cNode.InnerText = text;
                    _find = true;
                    return cNode;
                }
            }
            if (!_find)
            {
                childNode = doc.CreateElement(Name);
                childNode.InnerText = text;
                node.AppendChild(childNode);
            }
            return childNode;
        }
    }
}
